<template>
<div>
	<canvas id="modelRenderCanvas"></canvas>
  <div class="tools-box">
	  	<div class="tool" data-title="IFC视图" @click="changeTool('treeView')">
			<d2-icon-svg class="tool-icon" name="treeview"/>
		</div>
		<div class="tool" @click="changeTool('markAnnotation')" data-title="打标记">
			<d2-icon-svg class="tool-icon" name='position'/>
		</div>
		<div class="tool" @click="changeTool('getGhost')" data-title="建筑骨架">
			<d2-icon-svg class="tool-icon" name='edit'/>
		</div>
		<div class="tool" @click="changeTool('photo')"  data-title="相机">
			<d2-icon-svg class="tool-icon" name='camera'/>
		</div>
		<div class="tool" @click="changeTool('default')"  data-title="HOME">
			<d2-icon-svg class="tool-icon" name='home'/>
		</div>
		<div class="tool" data-title="创建组件集合" @click="changeTool('collection')">
			<d2-icon-svg class="tool-icon" name='plantcollections'/>
		</div>
		<div class="tool" data-title="批注" @click="changeTool('makeNote')">
			<d2-icon-svg class="tool-icon" name='note'/>
		</div>
		<div class="tool" data-title="剖面" @click="changeTool('displayProfile')">
			<d2-icon-svg class="tool-icon" name='profile'/>
		</div>
		<div class="tool" data-title="材质上色" @click="changeTool('colorToMeterail')">
			<d2-icon-svg class="tool-icon" name='note'/>
		</div>
		<div class="tool" data-title="抽屉功能" @click="changeTool('drawer')">
			<d2-icon-svg class="tool-icon" name='menu'/>
		</div>
		<div class="tool" data-title="楼层模式" @click="changeTool('eye')">
			<d2-icon-svg class="tool-icon" name='eye'/>
		</div>
		<div class="tool" data-title="组件属性查看" @click="changeTool('componentDetail')">
			<d2-icon-svg  class="tool-icon"  name="componentDetailInfo"/>
		</div>
		<div class="tool" data-title="第一人称漫游" @click="changeTool('firstPerson')">
			<d2-icon-svg  class="tool-icon"  name="firstPerson"/>
		</div>
	    <div class="tool" data-title="模拟施工" @click="changeTool('simulatedConstruction')">
			<d2-icon-svg class="tool-icon" name="simulatedConstruction"/>
        </div>
		<div class="tool" data-title="爆炸模式" @click="changeTool('boom')">
			<d2-icon-svg  class="tool-icon"  name="right"/>
		</div>
		<div class="tool" data-title="多模型加载" @click="changeTool('addModel')">
			<d2-icon-svg  class="tool-icon"  name="firstPerson"/>
		</div>
  </div>
	<div class="toolcomponent-container">
		<!--工具组件切换容器,keep-alive组件防止组件重复创建，导致多次注册pick事件处理程序而出现的问题-->
		<keep-alive>
			<div v-bind:is="currentTool.toolComponent" :currentTool="currentTool.toolName"
				 :storeyDatas="storeyDatas"
			     :movieData="movieData"></div>
		</keep-alive>
	</div>
</div>
</template>

<script>
import * as xeogl from '@/libs/xeogl/base/xeogl.module'
import Utils from '@/components/bim/treeview/js/Utils'
import IfcTreeView from "../../components/bim/treeview/IfcTreeView"
import ComponentCollections from '../../components/bim/componentCollections/ComponentCollections'
import ColorToMeterial from '../../components/bim/colorToMeterial/ColorToMeterial'
import ComponentDetailInformation from '../../components/bim/componentDetailInformation/ComponentDetailInformation'
import SimulatedConstruction from '../../components/bim/simulatedConstruction/SimulatedConstruction'
import D2IconSvg from "../../components/d2-icon-svg/index"
import KeyEvent from '../../components/bim/componentCollections/KeyEvent'
import boomComponent from '../../components/bim/boom/boom'
import drawerComponent from '../../components/bim/drawer/drawer'
import storeyComponent from '../../components/bim/storey/storey'
import profileComponent from '../../components/bim/profile/profile'
import photoComponent from '../../components/bim/photo/photo'
import firstPersonComponent from '../../components/bim/firstPerson/firstPerson'
import { setInterval, clearInterval } from 'timers';
import { connect } from 'tls';
// import treeViewApi from '@/components/bim/treeview/TreeViewApi';
// window.treeViewApi = treeViewApi;
window.xeogl = xeogl;
require( '@/libs/xeogl/extends/models/glTFModel')
require('@/libs/xeogl/extends/geometry/vectorTextGeometry')
require('@/libs/xeogl/extends/helpers/axisHelper')
require('@/libs/xeogl/extends/annotations/pin')
require('@/libs/xeogl/extends/annotations/annotation')
require('@/libs/xeogl/extends/annotations/annotation-style.css')
require('@/libs/xeogl/extends/curves/curve')
require('@/libs/xeogl/extends/curves/splineCurve')
require('@/libs/xeogl/extends/animation/cameraPath')
require('@/libs/xeogl/extends/animation/cameraPathAnimation')
require('@/libs/xeogl/extends/helpers/planeHelper')
require('@/libs/xeogl/extends/helpers/clipHelper')


let model, camera, scene, cameraControl, input,
cameraFlight, lastEntity, lastColorize, willUse,
annotations, keyEvent,imgs, frames, cameraPath,cameraPathAnimation,selectColor,
movieId, movieFrames, isStart;

/**
 * 全局访问对象，其它地方取用里面的属性进行使用，例如model
 */
window.GOLOAlBAL_OPEOBJ = {};
export default {
	components: {
		D2IconSvg,
		IfcTreeView,
		ComponentCollections,
		ColorToMeterial,
        ComponentDetailInformation,
		boomComponent,
		drawerComponent,
		storeyComponent,
		profileComponent,
		photoComponent,
		firstPersonComponent
	},
	data:function(){
		return {
			model:{},
			showProfile: false,
			showDrawer: false,
			showStorey: false,
			showFirstPerson: false,
			inputMovieName: false,
			showBoom: false,
			currentTool:{toolName:"",toolComponent:""},
			storeyDatas: [],
			movieData: []
		}
	},
	methods: {
		initModel: function() {
			model = new xeogl.GLTFModel({
				canvasId:"modelRenderCanvas",
				src: "models/gltf/houseDemo1213.gltf",
				handleNode: (function() {
					var objectCount = 0;
					return function (nodeInfo, actions) {
						if (nodeInfo.mesh !== undefined) { // Node has a mesh
							var code = (nodeInfo.name).match(/(product-)(.*)(-body)/)[2].replace(/-/g,"");
							var guid = Utils.compressGuid(code);
							if(guid==="2ZKYCuA$v0cwhh$jJcKHKX"){
							    console.log(guid);
							}
							actions.createObject = {
								id: guid
							};
						}
						return true;
					};
				})(),
				scale:[1,1,1]
			});
			model.on("loaded", function () {
				GOLOAlBAL_OPEOBJ.bimModel = model;
			});
		},
		initCamera: function() {
			camera = model.scene.camera;
			camera.eye = [1, 1, 1];
			camera.look = [0, -0.00, 11.18];
			camera.up = [0, 1, 0];
			GOLOAlBAL_OPEOBJ.camera=camera
		},
		initScene: function() {
			scene = xeogl.getDefaultScene();
			GOLOAlBAL_OPEOBJ.scene = scene;
			//scene.objects["3dnoSLa IT1ZA6bPkTCQI$B"].highlighted = true;
		},
		initKeyEvent:function () {
			keyEvent = KeyEvent.getInstance({});
				GOLOAlBAL_OPEOBJ.keyEvent = KeyEvent.getInstance({});
			},
		initInput: function() {
			input = scene.input;
			selectColor = [0.0, 1.0, 0.0, 1.0];

			input.on("mouseclicked", function(coords) {
				let hit = scene.pick({
					canvasPos: coords
				});

				if (hit) {
					if (!lastEntity || hit.mesh.id !== lastEntity.id) {
						if (lastEntity) {
							lastEntity.colorize = lastColorize;
						}
						lastEntity = hit.mesh;
						lastColorize = hit.mesh.colorize.slice();
						hit.mesh.colorize = selectColor;
					} else {
						if(lastEntity) {
							lastEntity.colorize = lastColorize;
							lastEntity = null;
						}
					}
				} else {
					if (lastEntity) {
						lastEntity.colorize = lastColorize;
						lastEntity = null;
					}
				}
			});
		},
		initCameraFlight: function() {
			cameraFlight = new xeogl.CameraFlightAnimation();
			GOLOAlBAL_OPEOBJ.cameraFlight = cameraFlight;
		},
		initCameraControl: function() {
			var self = this;
			cameraControl = new xeogl.CameraControl({});

			cameraControl.on("picked", function (hit) {
				if (scene.input.keyDown[input.KEY_SHIFT]) {
					hit.mesh.selected = !hit.mesh.selected;
				} else {
					cameraFlight.flyTo(hit.mesh);
				}
 			});

			cameraControl.on("pickedNothing", function (hit) {
				cameraFlight.flyTo(model);
			});
			cameraControl.on("picked", function (e) {
				if(willUse) {
					willUse.call(this, e)
				}
			});
			GOLOAlBAL_OPEOBJ.cameraControl = cameraControl;
		},
		initAxisHelper: function() {
			var AxisHelper = new xeogl.AxisHelper({
				camera: scene.camera,
				size: [200, 200],
				visible: true
			});
			GOLOAlBAL_OPEOBJ.AxisHelper = AxisHelper;
		},
		initCameraPathAnimation: function() {
			if(!cameraPath) {
				cameraPath = new xeogl.CameraPath({
				});
			}
			cameraPathAnimation = new xeogl.CameraPathAnimation({
				cameraPath: cameraPath,
        playingRate: 0.5
			})
			GOLOAlBAL_OPEOBJ.cameraPathAnimation = cameraPathAnimation
			GOLOAlBAL_OPEOBJ.cameraPath = cameraPath
		},
		init: function() {
			this.initModel()
			this.initCamera()
			this.initScene()
			this.initCameraFlight()
			this.initKeyEvent()
			this.initInput()
			this.initCameraControl()
			this.initAxisHelper()
			this.initCameraPathAnimation()
		},
		changeTool: function(tool) {
		    //标识当前打开的工具
			//this.currentTool.toolName = tool;
			alert(tool==='boom');
			if(tool === 'markAnnotation') {
				willUse = this.markAnnotation
				document.body.style.cursor = 'pointer'
			} else if(tool === 'default') {
				document.body.style.cursor = 'default'
				willUse = null
			} else if(tool === 'getGhost') {
				model.ghosted = !model.ghosted;
			} else if(tool==='treeView'){
                this.checkToolComponent('treeView',IfcTreeView);
			} else if(tool==='collection'){
                this.checkToolComponent('collection',ComponentCollections);
			} else if(tool==='colorToMeterail'){
                this.checkToolComponent('colorToMeterail',ColorToMeterial);
			} else if(tool==='componentDetail'){
                this.checkToolComponent('componentDetail',ComponentDetailInformation);
			} else if(tool==='simulatedConstruction'){
				this.checkToolComponent('simulatedConstruction',SimulatedConstruction);
			} else if(tool==='displayProfile') {
				this.checkToolComponent('profileComponent',profileComponent)
			} else if(tool==='makeNote') {
			    this.makeNote();
			} else if(tool === 'photo') {
				this.checkToolComponent('photoComponent',photoComponent)
			} else if(tool === 'drawer') {
				this.checkToolComponent('drawerComponent',drawerComponent);
			} else if(tool === 'eye') {
				this.checkToolComponent('storeyComponent',storeyComponent);
			} else if(tool === 'firstPerson') {
				this.checkToolComponent('firstPersonComponent',firstPersonComponent)
			} else if(tool === 'boom') {
				this.checkToolComponent('boomComponent',boomComponent);
			} else if(tool === 'addModel') {
				this.addModel();
			}
		},
        /**
		 * toggle切换工具栏
         * @param toolName
         * @param toolComponent
         */
		checkToolComponent:function (toolName,toolComponent) {
            if(this.currentTool.toolComponent!=""&&this.currentTool.toolName === toolName){
                this.currentTool.toolComponent = "";
                this.currentTool.toolName = "";
                return;
            }
            this.currentTool.toolName = toolName;
            this.currentTool.toolComponent = toolComponent;
        },
		markAnnotation: function(e) {
			if(!annotations) {
				annotations = []
			}
			let index = annotations.length + 1

			// console.log('primaIndex: ' + )
			let temp = new xeogl.Annotation({
				mesh: e.mesh,
				primIndex: e.primIndex,
				bary: e.bary,
				occludable: true,
				glyph: index,
				title: 'First',
				eye: camera.eye,
				look: camera.look,
				up: camera.up,
				desc: "CLU hops in and out of the tank program here",
				pinShown: true,
				labelShown: false
			})
			annotations.push(temp)
		},
		openDialog(){

		},
		makeNote: function() {

		},
		addModel: function() {
			// let man = new xeogl.GLTFModel({
			// 	id: 'man',
			// 	canvasId:"modelRenderCanvas",
			// 	src: "models/gltf/Halifax_Bomber.gltf"
			// })

			// man.on("loaded", function () {
			// 	GOLOAlBAL_OPEOBJ.addModel = man;
			// 	man.position = [15, 0, 10];
			// 	man.rotateY(-150);
			// });

			model.addChild(new xeogl.Mesh({
        geometry: new xeogl.Geometry({
						primitive: "triangles",
						position : [15, 0, 10],
            positions: [
                // v0-v1-v2-v3 front
                2, 2, 2,
                -2, 2, 2,
                -2, -2, 2,
                2, -2, 2,
                // v0-v3-v4-v1 right
                2, 2, 2,
                2, -2, 2,
                2, -2, -2,
                2, 2, -2,
                // v0-v1-v6-v1 top
                2, 2, 2,
                2, 2, -2,
                -2, 2, -2,
                -2, 2, 2,
                // v1-v6-v7-v2 left
                -2, 2, 2,
                -2, 2, -2,
                -2, -2, -2,
                -2, -2, 2,
                // v7-v4-v3-v2 bottom
                -2, -2, -2,
                2, -2, -2,
                2, -2, 2,
                -2, -2, 2,
                // v4-v7-v6-v1 back
                2, -2, -2,
                -2, -2, -2,
                -2, 2, -2,
                2, 2, -2
            ],
            normals: [
                // v0-v1-v2-v3 front
                0, 0, 1,
                0, 0, 1,
                0, 0, 1,
                0, 0, 1,
                // v0-v3-v4-v5 right
                1, 0, 0,
                1, 0, 0,
                1, 0, 0,
                1, 0, 0,
                // v0-v5-v6-v1 top
                0, 1, 0,
                0, 1, 0,
                0, 1, 0,
                0, 1, 0,
                // v1-v6-v7-v2 left
                -1, 0, 0,
                -1, 0, 0,
                -1, 0, 0,
                -1, 0, 0,
                // v7-v4-v3-v2 bottom
                0, -1, 0,
                0, -1, 0,
                0, -1, 0,
                0, -1, 0,
                // v4-v7-v6-v5 back
                0, 0, -1,
                0, 0, -1,
                0, 0, -1,
                0, 0, -1
            ],
            indices: [
                0, 1, 2,
                0, 2, 3,
                // front
                4, 5, 6,
                4, 6, 7,
                // right
                8, 9, 10,
                8, 10, 11,
                // top
                12, 13, 14,
                12, 14, 15,
                // left
                16, 17, 18,
                16, 18, 19,
                // bottom
                20, 21, 22,
                20, 22, 23
            ]
        }),
        material: new xeogl.PhongMaterial({
            diffuse: [0.6, 0.6, 1.0]
        })
    }))
		}
	},
  created() {
		this.init()
  }
}
</script>
<style>
	@import "design.css";
</style>
